package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.adapter.MyNewsHomeAdapter;
import com.sczmgk.hotline_pzh.base.BaseActivity;
import com.sczmgk.hotline_pzh.callback.HttpFailCallback;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.InformationBean;
import com.sczmgk.hotline_pzh.entity.NewsHomeBean;
import com.sczmgk.hotline_pzh.entity.NewsHomeBean.NewsInfos;
import com.sczmgk.hotline_pzh.entity.Picurls;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.utils.UIUtils;
import com.sczmgk.hotline_pzh.view.MyNewsListView;
import com.sczmgk.hotline_pzh.view.MySearchListView;
import com.sczmgk.hotline_pzh.view.NoDoubleItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sczmgk.hotline_pzh.MyApp.bitmapUtils;


/**
 * Created by Administrator on 2016/12/1 0001.
 */
public class NewsHomeActivity extends BaseActivity {

    /*资讯的信息*/
    private static final int NEWS_INFO = 1;

    /*请求码*/
    private static final int REQUEST_CODE = 100;

    /*顶部热点的ViewPager*/
    private ViewPager mVpNews;

    /*热点的底部标题和显示页数*/
    private TextView mTvTitle;
    private TextView mTvCurrentPage;
    private TextView mTvDivider;
    private TextView mTvTotalPage;

    /*带有搜索框的ListView*/
    private MySearchListView mLvNews;

    /*存储资讯信息的集合*/
    private List<NewsInfos> newsLists;

    /*存储热点信息的集合*/
    private List<InformationBean> hotInfos;

    /*热点信息的Adapter*/
    private MyViewpagerAdapter hotAdapter;

    /*资讯信息的Adapter*/
    private MyAdapter newsAdapter;

    /*热点无限轮播的Handler*/
    private MyHandler myHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_home);

        setHeader();

        initView();

        initData();

        setListener();

        myHandler = new MyHandler();
    }

    /**
     * 设置头
     */
    private void setHeader() {
        setTitle(R.string.title_latest_news);
        setLeftBtnVisibility(View.VISIBLE);
    }

    /**
     * 初始化控件
     */
    private void initView() {

        //带有搜索框的ListView
        mLvNews = (MySearchListView) findViewById(R.id.lv_news);

        //加载顶部热点布局
        View headerView = View.inflate(NewsHomeActivity.this, R.layout.news_home_view_pager, null);

        //热点详情的ViewPager
        mVpNews = (ViewPager) headerView.findViewById(R.id.vp_news);
        mTvTitle = (TextView) headerView.findViewById(R.id.tv_view_pager_title);
        mTvCurrentPage = (TextView) headerView.findViewById(R.id.tv_viewpager_current_page);
        mTvDivider = (TextView) headerView.findViewById(R.id.tv_viewpager_divider);
        mTvTotalPage = (TextView) headerView.findViewById(R.id.tv_viewpager_total_page);

        //将热点添加为资讯ListView的头
        mLvNews.addHeaderView(headerView);

    }

    /**
     * 初始化数据
     */
    private void initData() {

        //创建资讯和热点的集合
        newsLists = new ArrayList<>();
        hotInfos = new ArrayList<>();

        //创建资讯和热点的Adapter
        newsAdapter = new MyAdapter();
        hotAdapter = new MyViewpagerAdapter();

        //设置资讯的adapter
        mLvNews.setAdapter(newsAdapter);

        //访问网络拉取数据
        getDataFromNet();
    }

    /**
     * 从网上获取资讯数据
     */
    private void getDataFromNet() {

        loadingDialog = DialogFactory.getLoadingDialog(NewsHomeActivity.this);
        DialogFactory.showDialog(loadingDialog);

        Map<String, Object> infos = new HashMap<>();
        infos.put("userid", CacheUtils.getIntData(NewsHomeActivity.this, Constants.LOGIN_UID, 0));
        infos.put("imei", MyApp.imei);

        MyHttp.requestByFailCallback(Constants.BASE_URL + Constants.GET_INFORMATIONS_URL, infos, MyHttp.GET, NewsHomeActivity.this, false, null, new SimplePaserJsonCallback() {

            @Override
            public void onVerifyIsNull() {
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
                DialogFactory.dismissLoadingDialog(loadingDialog);
                try {
                    paserDataJson(dataRaw, isCache);
                } catch (Exception e) {
                    MyLog.e(TAG, "解析json错误");
                    e.printStackTrace();
                }
            }

            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                super.onErrorCodeError(mError);
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }
        }, new HttpFailCallback() {
            @Override
            public void onServiceErrorCallback() {
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }
        });

    }

    /**
     * 解析Json数据
     *
     * @param dataRaw
     * @param isCache
     */
    private void paserDataJson(String dataRaw, boolean isCache) {

        if (Tools.isEmpty(dataRaw)) {
            MyLog.i("获取资讯主页数据", "get news data json error");
            return;
        }

        //解析数据并将数据添加到集合中
        Gson gson = new Gson();
        NewsHomeBean newsHomeBean = gson.fromJson(dataRaw, NewsHomeBean.class);

        if (newsLists.size() > 0){
            newsLists.clear();
        }

        if (hotInfos.size() > 0){
            hotInfos.clear();
        }

        newsLists.addAll(newsHomeBean.datalist);
        hotInfos.addAll(newsHomeBean.hotlist);

        //发送消息更新ui
        mHandler.sendEmptyMessage(NEWS_INFO);
    }

    /**
     * 设置监听
     */
    private void setListener() {
    }


    @Override
    public void handleMessage(Message msg) {

        switch (msg.what) {

            case NEWS_INFO:

                newsAdapter.notifyDataSetChanged();

                mVpNews.setAdapter(hotAdapter);

                setViewPager();

                break;
        }

    }

    /**
     * 资讯模块的Adapter
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return newsLists == null ? 0 : newsLists.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            view = View.inflate(NewsHomeActivity.this, R.layout.item_news_home, null);

            final MyNewsListView lvItemNews = (MyNewsListView) view.findViewById(R.id.lv_item_news_home);

            final NewsInfos newsInfos = newsLists.get(i);

            lvItemNews.setAdapter(new MyNewsHomeAdapter(NewsHomeActivity.this, newsInfos.datalist));

            //设置资讯模块顶部头的标题
            lvItemNews.setTitleText(newsInfos.title);

            //设置资讯模块顶部头的图标
            lvItemNews.setNewsIcon(newsInfos.picurl);

            //更多的点击事件
            MyLog.d(TAG,"设置更多监听------> 模块名: "+ newsInfos.title);
            lvItemNews.setOnLoadMoreClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    UIUtils.startActivity(NewsHomeActivity.this, MoreDetailActivity.class, Constants.MORE_NEWS_TYPE, newsInfos.type, Constants.MORE_NEWS_TITLE, lvItemNews.getTitleText());
                }
            });

            //条目的点击事件
            lvItemNews.setOnItemClickListener(new NoDoubleItemClickListener() {
                @Override
                public void NoDoubleItemClickListener(AdapterView<?> parent, View view, int i, long id) {
                    int position = i - 1;
                    //跳转资讯相关详情界面

//                    IndicatorInfos byQuery = InformationTitleDaoImpl.getIntance(NewsHomeActivity.this).findByQuery(newsInfos.type);
//                    String title=null;
//                    if(byQuery != null){
//
//                         title = byQuery.title;
//                    }
                    InformationBean informationBean = newsInfos.datalist.get(position);
                    Intent intent = new Intent(NewsHomeActivity.this, NewsDetailActivity.class);
//                    intent.putExtra(Constants.MORE_NEWS_TITLE,title);
                    intent.putExtra(Constants.NEWS_DETAIL_ITEM, informationBean);
                    startActivityForResult(intent, REQUEST_CODE);
                }
            }) ;

            return view;
        }
    }

    /**
     * 热点的ViewPager
     */
    private class MyViewpagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return hotInfos == null ? 0 : hotInfos.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {

            final InformationBean newsInfo = hotInfos.get(position);

            View itemView = View.inflate(NewsHomeActivity.this, R.layout.item_news_viewpager, null);
            ImageView imageView = (ImageView) itemView.findViewById(R.id.iv_news_item_viewpager);

//            for (Picurls picurl : newsInfo.picurls) {
            List<Picurls> picurls = newsInfo.picurls;
            if (picurls != null && picurls.size() > 0) {
                bitmapUtils.display(imageView, newsInfo.picurls.get(0).smallpic);
            }
//            }

            container.addView(itemView);

//            imageView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    Intent intent = new Intent(NewsHomeActivity.this, NewsDetailActivity.class);
//                    intent.putExtra(Constants.NEWS_DETAIL_ITEM, newsInfo);
//                    startActivityForResult(intent, REQUEST_CODE);
//                }
//            });

            return itemView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    /**
     * 设置热点ViewPager
     */
    private void setViewPager() {

        //处理轮播图
        processPlay();

        //设置文本的改变
        mVpNews.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                InformationBean newsInfo = hotInfos.get(position);
                mTvTitle.setText(newsInfo.title);
                mTvCurrentPage.setText(String.valueOf(position + 1));
                mTvDivider.setText("/");
                mTvTotalPage.setText(String.valueOf(hotInfos.size()));
            }
        });

        if (hotInfos != null && hotInfos.size() > 0) {
            InformationBean newsInfo = hotInfos.get(0);
            mTvTitle.setText(newsInfo.title);
            mTvCurrentPage.setText(String.valueOf(1));
            mTvDivider.setText("/");
            mTvTotalPage.setText(String.valueOf(hotInfos.size()));
        }

        hotAdapter.notifyDataSetChanged();

    }

    /**
     * 处理无限轮播
     */
    private void processPlay() {

        // 发送延迟消息，切换轮播图
        if (myHandler == null) {
            myHandler = new MyHandler();
        }
        // 把前面发送的消息删除
        myHandler.removeCallbacksAndMessages(null);// null 删除所有的Callbacks 和Messages
        myHandler.sendMessageDelayed(Message.obtain(), 3000);

    }

    /**
     * 实现Banner的无限循环播放
     */
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {

            if (hotInfos != null && hotInfos.size() > 0) {

                // 实现无限循环，再次发生消息
                myHandler.sendMessageDelayed(Message.obtain(), 3000);

                // 把轮播图切换到下一张
                int item = (mVpNews.getCurrentItem() + 1) % hotInfos.size();

                if (item == 0) {// 从最后一张到第一张时，不要动画效果
                    mVpNews.setCurrentItem(item, false);
                } else {
                    mVpNews.setCurrentItem(item);
                }
            }
            super.handleMessage(msg);
        }
    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }

    @Override
    protected void onDestroy() {
        if (myHandler != null) {
            myHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        processPlay();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (myHandler != null){
            myHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
        super.onActivityResult(requestCode, resultCode, arg2);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                getDataFromNet();
            }
        }
    }

}
